"""
OCR Service - PaddleOCR Integration
Handles optical character recognition for images and scanned documents
"""

import os
from typing import List, Tuple, Optional
from pathlib import Path
import logging
from PIL import Image

logger = logging.getLogger(__name__)

class OCRService:
    """OCR服务 - 使用PaddleOCR进行文字识别"""
    
    def __init__(self):
        """初始化OCR引擎"""
        self.ocr_engine = None
        self._initialized = False
    
    def _lazy_init(self):
        """延迟初始化OCR引擎（首次使用时加载）"""
        if self._initialized:
            return
        
        try:
            from paddleocr import PaddleOCR
            
            # 初始化PaddleOCR
            # use_angle_cls=True 启用文字方向检测
            # lang='ch' 支持中英文混合识别
            self.ocr_engine = PaddleOCR(
                use_angle_cls=True,
                lang='ch',
                show_log=False
            )
            self._initialized = True
            logger.info("✅ PaddleOCR引擎初始化成功")
            
        except Exception as e:
            logger.error(f"❌ PaddleOCR初始化失败: {str(e)}")
            raise
    
    def extract_text_from_image(self, image_path: str) -> Tuple[str, List[dict]]:
        """
        从图片中提取文字
        
        Args:
            image_path: 图片文件路径
            
        Returns:
            Tuple[str, List[dict]]: (完整文本, 识别详情列表)
        """
        self._lazy_init()
        
        try:
            # 检查文件是否存在
            if not os.path.exists(image_path):
                raise FileNotFoundError(f"图片文件不存在: {image_path}")
            
            # 执行OCR识别
            logger.info(f"开始OCR识别: {image_path}")
            result = self.ocr_engine.ocr(image_path, cls=True)
            
            if not result or not result[0]:
                logger.warning(f"未检测到文字: {image_path}")
                return "", []
            
            # 提取文字和坐标信息
            full_text_lines = []
            details = []
            
            for line in result[0]:
                # line格式: [坐标, (文字, 置信度)]
                box = line[0]  # [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
                text_info = line[1]  # (text, confidence)
                text = text_info[0]
                confidence = text_info[1]
                
                full_text_lines.append(text)
                details.append({
                    "text": text,
                    "confidence": float(confidence),
                    "box": box
                })
            
            full_text = "\n".join(full_text_lines)
            
            logger.info(f"✅ OCR识别完成: 识别到 {len(details)} 行文字")
            logger.debug(f"识别文本预览: {full_text[:100]}...")
            
            return full_text, details
            
        except Exception as e:
            logger.error(f"❌ OCR识别失败: {str(e)}")
            raise
    
    def extract_text_from_pdf_images(self, pdf_path: str, output_dir: Optional[str] = None) -> str:
        """
        从PDF文件中提取图片并进行OCR识别
        
        Args:
            pdf_path: PDF文件路径
            output_dir: 图片输出目录（可选）
            
        Returns:
            str: 所有页面的识别文本
        """
        import fitz  # PyMuPDF
        
        try:
            doc = fitz.open(pdf_path)
            all_text = []
            
            # 创建临时目录存储提取的图片
            if output_dir is None:
                output_dir = os.path.join(os.path.dirname(pdf_path), "temp_ocr_images")
            os.makedirs(output_dir, exist_ok=True)
            
            logger.info(f"开始处理PDF: {pdf_path}, 共 {len(doc)} 页")
            
            for page_num in range(len(doc)):
                page = doc[page_num]
                
                # 将页面渲染为图片
                pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))  # 2倍缩放提高清晰度
                img_path = os.path.join(output_dir, f"page_{page_num + 1}.png")
                pix.save(img_path)
                
                # OCR识别
                try:
                    text, _ = self.extract_text_from_image(img_path)
                    if text.strip():
                        all_text.append(f"--- 第 {page_num + 1} 页 ---\n{text}")
                except Exception as e:
                    logger.warning(f"⚠️ 第 {page_num + 1} 页OCR失败: {str(e)}")
                    continue
            
            doc.close()
            
            # 清理临时图片
            import shutil
            if os.path.exists(output_dir):
                shutil.rmtree(output_dir)
            
            full_text = "\n\n".join(all_text)
            logger.info(f"✅ PDF OCR完成: 共识别 {len(all_text)} 页")
            
            return full_text
            
        except Exception as e:
            logger.error(f"❌ PDF OCR识别失败: {str(e)}")
            raise
    
    def is_image_file(self, filename: str) -> bool:
        """
        判断文件是否为图片
        
        Args:
            filename: 文件名
            
        Returns:
            bool: 是否为图片文件
        """
        image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif', '.webp', '.gif'}
        return Path(filename).suffix.lower() in image_extensions
    
    def get_image_info(self, image_path: str) -> dict:
        """
        获取图片信息
        
        Args:
            image_path: 图片文件路径
            
        Returns:
            dict: 图片信息（宽度、高度、格式等）
        """
        try:
            with Image.open(image_path) as img:
                return {
                    "width": img.width,
                    "height": img.height,
                    "format": img.format,
                    "mode": img.mode,
                    "size_bytes": os.path.getsize(image_path)
                }
        except Exception as e:
            logger.error(f"❌ 获取图片信息失败: {str(e)}")
            return {}


# 全局OCR服务实例
ocr_service = OCRService()

